import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/biorhythm.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';
import 'package:geomancy/widgets/common_vertical_text.dart';
import 'package:geomancy/widgets/stroke_text.dart';

class HealthHumanRhythmPage extends StatefulWidget {
  final String birthday;
  const HealthHumanRhythmPage({super.key, required this.birthday});

  @override
  State<HealthHumanRhythmPage> createState() => _HealthHumanRhythmPageState();
}

class _HealthHumanRhythmPageState extends State<HealthHumanRhythmPage> {
  final double progress = 0.7;  // 进度值 (0 到 1)
  /// FlSpot x, y 值
  List<FlSpot> spots = [];
  List<FlSpot> spots1 = [];
  List<FlSpot> spots2 = [];

  late Map<String, dynamic> rhythms;
  ///综合指数
  late double percent;


  @override
  void initState() {
    super.initState();
    // 假设出生日期为 1990-01-01
    DateTime birthDate = DateTime.parse(widget.birthday);
    // 计算当前日期（或者可以指定目标日期）
    DateTime targetDate = DateTime.now();
    // 计算生物节律
    rhythms = Biorhythm.calculateBioRhythms(birthDate, targetDate);
    // 获取未来30天的节律数据
    List<List<FlSpot>> future30DaysData = Biorhythm.generateFuture30DaysData(targetDate);
    spots = future30DaysData[0];
    spots1 = future30DaysData[1];
    spots2 = future30DaysData[2];
  }

  ///日期
  Widget timer() {
    // 获取当前日期
    final now = DateTime.now();
    final month = now.month.toString().padLeft(2, '0');  // 月份，补零
    final day = now.day.toString().padLeft(2, '0');      // 日期，补零
    
    return Row(
      children: [
        Container(
          width: 40.w,
          height: 40.w,
          margin: EdgeInsets.symmetric(horizontal: 2.w),
          decoration: BoxDecoration(
            color: ColorStyle.themeColor,
            borderRadius: BorderRadius.all(Radius.circular(8.w))
          ),
          alignment: Alignment.center,
          child: CommonText(txt: month, fontSize: 24.sp)
        ),
        const CommonText(txt: '月'),
        Container(
          width: 40.w,
          height: 40.w,
          margin: EdgeInsets.symmetric(horizontal: 2.w),
          decoration: BoxDecoration(
            color: ColorStyle.themeColor,
            borderRadius: BorderRadius.all(Radius.circular(8.w))
          ),
          alignment: Alignment.center,
          child: CommonText(txt: day, fontSize: 24.sp)
        ),
        const CommonText(txt: '日'),
      ],
    );
  }
  ///表格标题
  Widget tableTitle(String txt) {
    return Container(
      width: double.infinity,
      height: 80.w,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          border: Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
      ),
      child: CommonText(txt: txt),
    );
  }
  ///表格行
  Widget tableRow({double? height, required String title, required String content, bool showBottomBorder = true}) {
    return Container(
      width: double.infinity,
      height: height,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          border: showBottomBorder
            ? Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
            : null
      ),
      child: Row(
        children: [
          Container(
            width: 80.w,
            height: double.infinity,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: Border(right: BorderSide(width: 1.w, color: ColorStyle.borderColor))
            ),
            child: CommonVerticalTextWidget(content: title, alignment: MainAxisAlignment.center),
          ),
          Expanded(child: Container(
            padding: EdgeInsets.symmetric(horizontal: 35.w),
            child: CommonText(height: 1.6, txt: content),
          ))
        ],
      )
    );
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context),
      backgroundColor: ColorStyle.pageDefaultColor,
      body: ListView(
        physics: const ClampingScrollPhysics(),
        padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, Constant.PAGEPADDING.w),
        children: [
          const CommonTitleWidget(txt: '人体节律'),
          ///引言
          Container(
            height: 320.w,
            margin: EdgeInsets.only(top: 20.w),
            padding: EdgeInsets.symmetric(horizontal: 40.w),
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: ColorStyle.themeLightColor,
                border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: const CommonText(txt: '生物节律是自然进化赋予生命的基本特征之一，人类和一切生物都要受到生物节律的控制与影响。人体生物节律是指体力节律、情绪节律和智力节律。每一个周期中又存在着高潮期、低潮期和临界期。由于它具有准确的时间性，因此，也称之为人体生物钟。',),
          ),
          ///人体曲线计算
          Container(
            height: 1270.w,
            margin: EdgeInsets.only(top: 20.w),
            padding: EdgeInsets.only(top: 50.w, left: 40.w, right: 40.w),
            decoration: BoxDecoration(
                color: ColorStyle.themeLightColor,
                border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 40.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const CommonText(txt: '今天'),
                      timer()
                    ],
                  ),
                ),
                ///圆环
                Container(
                  width: 300.w,
                  height: 300.w,
                  margin: EdgeInsets.only(top: 30.w, bottom: 40.w),
                  child: Stack(
                    children: [
                      PieChart(
                        PieChartData(
                          borderData: FlBorderData(show: false),  // 不显示边框
                          sectionsSpace: 0,  // 每个区域之间的间距为0，保证形成圆环
                          centerSpaceRadius: 75,  // 圆心半径，形成圆环的效果
                          startDegreeOffset: 270,
                          sections: [
                            PieChartSectionData(
                              value: progress * 100,  // 进度值 (百分比)
                              color: ColorStyle.pageDefaultColor,  // 进度条颜色
                              title: '',
                              radius: 12,  // 外圈半径
                              showTitle: false,
                            ),
                            PieChartSectionData(
                              value: (1 - progress) * 100,  // 剩余部分
                              color: ColorStyle.borderColor,  // 剩余部分颜色
                              title: '',
                              radius: 12,  // 外圈半径
                              showTitle: false,
                            ),
                          ],
                        ),
                      ),
                      Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            StrokeText(txt: '${rhythms['average']['value']}%', fontSize: 80.sp, fontFamily: 'fontZKKLT'),
                            const CommonText(txt: '综合指数'),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                ///体力
                Container(
                  height: 100.w,
                  padding: EdgeInsets.only(left: 3.w, right: 40.w),
                  margin: EdgeInsets.only(bottom: 20.w),
                  decoration: BoxDecoration(
                    border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                    borderRadius: BorderRadius.all(Radius.circular(50.w))
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      ClipOval(
                        child: Container(
                          width: 84.w,
                          height: 84.w,
                          color: const Color.fromRGBO(167, 209, 82, 1),
                          alignment: Alignment.center,
                          child: CommonText(txt: '体力', fontSize: 24.sp),
                        ),
                      ),
                      SizedBox(width: 15.w),
                      Expanded(child: Row(
                        children: List.filled(5, 0).asMap().keys.map((index) {
                          final int activeIndex = rhythms['Physical']['category'];
                          return Image.asset(activeIndex >= index ? 'assets/icons/icon_physical_active.png' : 'assets/icons/icon_physical.png', width: 60.w);
                        }).toList(),
                      )),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          CommonText(txt: '下次顶峰', fontSize: 24.sp),
                          CommonText(txt: '${rhythms['Physical']['day']}天后'),
                        ],
                      )
                    ],
                  ),
                ),
                ///情绪
                Container(
                  height: 100.w,
                  padding: EdgeInsets.only(left: 3.w, right: 40.w),
                  margin: EdgeInsets.only(bottom: 20.w),
                  decoration: BoxDecoration(
                      border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                      borderRadius: BorderRadius.all(Radius.circular(50.w))
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      ClipOval(
                        child: Container(
                          width: 84.w,
                          height: 84.w,
                          color: const Color.fromRGBO(132, 208, 228, 1),
                          alignment: Alignment.center,
                          child: CommonText(txt: '情绪', fontSize: 24.sp),
                        ),
                      ),
                      SizedBox(width: 15.w),
                      Expanded(child: Row(
                        children: List.filled(5, 0).asMap().keys.map((index) {
                          final int activeIndex = rhythms['Emotional']['category'];
                          return Image.asset(activeIndex >= index ? 'assets/icons/icon_emotional_active.png' : 'assets/icons/icon_emotional.png', width: 60.w);
                        }).toList(),
                      )),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          CommonText(txt: '下次顶峰', fontSize: 24.sp),
                          CommonText(txt: '${rhythms['Emotional']['day']}天后'),
                        ],
                      )
                    ],
                  ),
                ),
                ///智力
                Container(
                  height: 100.w,
                  padding: EdgeInsets.only(left: 3.w, right: 40.w),
                  margin: EdgeInsets.only(bottom: 20.w),
                  decoration: BoxDecoration(
                      border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                      borderRadius: BorderRadius.all(Radius.circular(50.w))
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      ClipOval(
                        child: Container(
                          width: 84.w,
                          height: 84.w,
                          color: const Color.fromRGBO(228, 85, 81, 1),
                          alignment: Alignment.center,
                          child: CommonText(txt: '智力', fontSize: 24.sp),
                        ),
                      ),
                      SizedBox(width: 15.w),
                      Expanded(child: Row(
                        children: List.filled(5, 0).asMap().keys.map((index) {
                          final int activeIndex = rhythms['Intellectual']['category'];
                          return Image.asset(activeIndex >= index ? 'assets/icons/icon_intellectual_active.png' : 'assets/icons/icon_intellectual.png', width: 60.w);
                        }).toList(),
                      )),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          CommonText(txt: '下次顶峰', fontSize: 24.sp),
                          CommonText(txt: '${rhythms['Intellectual']['day']}天后'),
                        ],
                      )
                    ],
                  ),
                ),
                Expanded(child: Container(
                  padding: EdgeInsets.symmetric(vertical: 40.w),
                  child: LineChart(
                    LineChartData(
                      gridData: const FlGridData(show: false),
                      titlesData: FlTitlesData(
                          topTitles: const AxisTitles(
                              sideTitles: SideTitles(
                                  showTitles: false
                              )
                          ),
                          leftTitles: const AxisTitles(
                              sideTitles: SideTitles(
                                  showTitles: false
                              )
                          ),
                          rightTitles: const AxisTitles(
                              sideTitles: SideTitles(
                                  showTitles: false
                              )
                          ),
                          bottomTitles: AxisTitles(
                            sideTitles: SideTitles(
                              showTitles: true,
                              getTitlesWidget: (double value, TitleMeta meta) {
                                return Container(
                                  margin: EdgeInsets.only(top: 4.w),
                                  child: CommonText(txt: value.toStringAsFixed(0), fontSize: 24.sp),
                                );
                              }
                            ),
                          )
                      ),
                      borderData: FlBorderData(show: false),
                      lineBarsData: [
                        ///体力曲线
                        LineChartBarData(
                          spots: spots,
                          isCurved: true,
                          color: const Color.fromRGBO(167, 209, 82, 1),
                          barWidth: 3.w,
                          dotData: const FlDotData(
                              show: false
                          ),
                          belowBarData: BarAreaData(
                            show: true,  // 显示曲线下方的区域
                            gradient: const LinearGradient(
                              begin: Alignment.topCenter,  // 渐变的起始点
                              end: Alignment.bottomCenter,  // 渐变的结束点
                              colors: [
                                Color.fromRGBO(167, 209, 82, 0.5),
                                Color.fromRGBO(228, 85, 81, 0),
                              ],
                            ),
                          ),
                        ),
                        ///情绪曲线
                        LineChartBarData(
                          spots: spots1,
                          isCurved: true,
                          color: const Color.fromRGBO(132, 208, 228, 1),
                          barWidth: 3.w,
                          dotData: const FlDotData(
                              show: false
                          ),
                          belowBarData: BarAreaData(
                            show: true,  // 显示曲线下方的区域
                            gradient: const LinearGradient(
                              begin: Alignment.topCenter,  // 渐变的起始点
                              end: Alignment.bottomCenter,  // 渐变的结束点
                              colors: [
                                Color.fromRGBO(132, 208, 228, 0.5),
                                Color.fromRGBO(132, 208, 228, 0),
                              ],
                            ),
                          ),
                        ),
                        ///智力曲线
                        LineChartBarData(
                          spots: spots2,
                          isCurved: true,
                          color: const Color.fromRGBO(228, 85, 81, 1),
                          barWidth: 3.w,
                          dotData: const FlDotData(
                              show: false
                          ),
                          belowBarData: BarAreaData(
                            show: true,  // 显示曲线下方的区域
                            gradient: const LinearGradient(
                              begin: Alignment.topCenter,  // 渐变的起始点
                              end: Alignment.bottomCenter,  // 渐变的结束点
                              colors: [
                                Color.fromRGBO(228, 85, 81, 0.5),
                                Color.fromRGBO(228, 85, 81, 0)
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ))
              ],
            ),
          ),
          ///体力节律
          Container(
            height: 1017.w,
            margin: EdgeInsets.only(top: 20.w),
            decoration: BoxDecoration(
                color: ColorStyle.themeLightColor,
                border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: Column(
              children: [
                tableTitle('体力节律'),
                tableRow(
                  height: 280.w,
                  title: '高潮期',
                  content: '体力充沛，身体灵活，动作敏捷，耐力和爆发力强，充满活力，能担负较大负荷的体力劳动，劳累后恢复得快;此时身体抗病能力强，不易感染疾病，治疗疾病效果明显。'
                ),
                tableRow(
                  height: 370.w,
                  title: '临界日',
                  content: '抵抗力低，免疫功能差，身体软弱无力，极易疲劳。易受外来各种不良因素的侵袭。有时表现的动作失常，运动员进行大运动量训练易受伤。慢性病极易复发或病情加重，是危重病人或老人的危险点，多数人往往死于临界日。'
                ),
                Expanded(child: tableRow(
                  showBottomBorder: false,
                  title: '低潮期',
                  content: '身体乏力、懒散，耐力和爆发力较差，劳动常感到力不从心易疲劳。比较容易感染疾病，特别是哮喘病极易发作。低潮期治病的效果一般不明显。'
                )),
              ],
            )
          ),
          ///情绪节律
          Container(
              height: 1277.w,
              margin: EdgeInsets.only(top: 20.w),
              decoration: BoxDecoration(
                  color: ColorStyle.themeLightColor,
                  border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                  borderRadius: BorderRadius.all(Radius.circular(60.w))
              ),
              child: Column(
                children: [
                  tableTitle('情绪节律'),
                  tableRow(
                    height: 380.w,
                    title: '高潮期',
                    content: '心情愉快，舒畅乐观，精力充沛，意志坚强，办事有信心，创造力、艺术感染力强。是创作的最好时期。思路灵活、敏捷，是解决矛盾，处理疑难问题的好时候。对待问题的态度积极且富有建设性。能与人融洽相处。经商贸易一般不易出错，效率也高。'
                  ),
                  tableRow(
                    height: 570.w,
                    title: '临界日',
                    content: '情绪不稳定，烦躁易怒，心绪不宁，精力特别不易集中。精神恍，工作易出差错，最易出交通、航空飞行和工伤事故。自制能力差，缺乏理智、容易冲动。一点小事都可能激怒人，人一旦被激怒常做出过火行为。是精神病、冠心病的发病期和危险期。白杀多发生在该阶段。有无事生非心态，做不好调工作。一些矛盾激化事件如打架斗殴、家庭邻里纠纷也多在此时发生。'
                  ),
                  Expanded(child: tableRow(
                    showBottomBorder: false,
                    title: '低潮期',
                    content: '情绪低落，精神不振，意志比较消沉。做事缺乏勇气，信心不足，注意力易分散，常感到烦躁不安或心绪不宁，此时也容易出工作差错和事故。'
                  )),
                ],
              )
          ),
          ///智力节律
          Container(
            height: 920.w,
            margin: EdgeInsets.only(top: 20.w),
            decoration: BoxDecoration(
              color: ColorStyle.themeLightColor,
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: Column(
              children: [
                tableTitle('智力节律'),
                tableRow(
                  height: 320.w,
                  title: '高潮期',
                  content: '头脑灵活，思维敏捷，思路清晰，记忆力强，精力和注意力集中。善于综合分析，判断准确，逻辑思维性强，工作效率和工作质量高。是学习、创造、写文章、决策、计算的最佳时机。'
                ),
                tableRow(
                  height: 280.w,
                  title: '临界日',
                  content: '判断力差、健忘、注意力涣散，严重者头脑发晕发胀，丢三忘四，工作中极易出差错和失误。此时不宜做计算、交易，最好也不强迫自己写文章。'
                ),
                Expanded(child: tableRow(
                  showBottomBorder: false,
                  title: '低潮期',
                  content: '思维显得迟钝，记忆力较弱。理解和构思联想比较缓慢，逻辑思维能力较弱，注意力不易集中，判断力往往降低，缺乏直觉、工作详细效率不高。'
                )),
              ],
            )
          ),
        ],
      ),
    );
  }
}
